package io.github.leon406.view.textview

import android.graphics.Color
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.view.ViewCompat
import io.github.leon406.view.span.ITouchableSpan

abstract class TouchClickSpan(
    @ColorInt var normalTextColor: Int = Color.BLUE,
    @ColorInt var pressedTextColor: Int = Color.YELLOW,
    @ColorInt var normalBackgroundColor: Int = Color.WHITE,
    @ColorInt var pressedBackgroundColor: Int = Color.BLUE
) : ClickableSpan(), ITouchableSpan {
    var hasUnderline = false
    var hasPressed = false
    override fun setPressed(pressed: Boolean) {
        hasPressed = pressed
    }

    abstract fun onSpanClick(widget: View?)
    override fun onClick(p0: View) {
        if (ViewCompat.isAttachedToWindow(p0)) {
            onSpanClick(p0)
        }
    }

    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        ds.run {
            isUnderlineText = hasUnderline
            color = if (hasPressed) pressedTextColor else normalTextColor
            bgColor = if (hasPressed) pressedBackgroundColor else normalBackgroundColor
        }
    }
}
